package com.kye.express.business.customer_intro.detail;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.databinding.ActivityCustomerIntroDetailBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.customer_intro.CustomerAppealResultBean;
import com.kye.model.bean.customer_intro.CustomerIntroHistoryResultBean;
import com.kye.model.bean.customer_intro.GetCustomerIntroDetailResultBean;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 客户介绍详情
 */
public class CustomerIntroDetailActivity extends BaseToolbarActivity implements CustomerIntroDetailActivityContract.CustomerIntroDetailActivityView {
    private static final String ARG_DATA = "data";
    private ActivityCustomerIntroDetailBinding mBinding;
    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private Dialog mLoadingDialog;
    private String mCompany = "";
    private CustomerIntroDetailActivityContract.CustomerIntroDetailActivityViewPresenter mPresenter;
    private CustomerIntroHistoryResultBean.DatasBean mOldData;
    private String mOrderNo;

    public static void startActivity(Context context, CustomerIntroHistoryResultBean.DatasBean datasBean) {
        Intent intent = new Intent(context, CustomerIntroDetailActivity.class);
        intent.putExtra(ARG_DATA, datasBean);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_customer_intro_detail);
        mPresenter = new CustomerIntroDetailActivityContract.CustomerIntroDetailActivityViewPresenter(this);
        mPresenter.bind(this);
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        setTitle(getString(R.string.customer_intro_intro_detail));
        mOldData = (CustomerIntroHistoryResultBean.DatasBean) getIntent().getSerializableExtra(ARG_DATA);
        if (mOldData != null) {
            mCompany = mOldData.getIntroductionToCompany();
            mBinding.setData(mOldData);
            mBinding.btnAppeal.setVisibility(mOldData.getStatusCode() == 1 ? View.VISIBLE : View.GONE);
            mBinding.edtGiveupReason.setVisibility(mOldData.getStatusCode() == 1 ? View.VISIBLE : View.GONE);
        }
        initView();
        initEvent();
        mPresenter.loadDatas(mCompany);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    private void initView() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(GetCustomerIntroDetailResultBean.DatasBean.class, new CustomerIntroDetailListItemViewBinder(this));
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerview.setHasFixedSize(true);
        mBinding.recyclerview.setNestedScrollingEnabled(false);
        RecyclerViewDivider.with(this)
                .color(getResources().getColor(R.color.grey))
                .size(ScreenUtils.dp2px(this, 10))
                .hideLastDivider()
                .build()
                .addTo(mBinding.recyclerview);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
    }

    private void initEvent() {
        RxView.clicks(mBinding.btnViewPhone)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mOldData != null) {
                            mBinding.tvPhone.setText(mOldData.getScTel());
                            mBinding.btnViewPhone.setVisibility(View.GONE);
                        }
                    }
                });

        RxView.clicks(mBinding.btnAppeal)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showAppealDialog();
                    }
                });
    }

    private void showAppealDialog() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View view = layoutInflater.inflate(R.layout.dialog_customer_intro_appeal_input, null);
        EditText contentView = view.findViewById(R.id.edt_appeal_content);
        new MaterialDialog.Builder(this)
                .title(R.string.customer_intro_appeal_reason)
                .customView(view, false)
                .positiveText(R.string.common_send)
                .negativeText(R.string.common_cancel)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        String reason = contentView.getText().toString();
                        if (TextUtils.isEmpty(reason)) {
                            ToastManager.show(CustomerIntroDetailActivity.this, R.string.customer_input_appeal_reason, Toast.LENGTH_SHORT);
                            return;
                        }
                        if (TextUtils.isEmpty(mOrderNo)) {
                            ToastManager.show(CustomerIntroDetailActivity.this, R.string.customer_intro_orderno_null, Toast.LENGTH_SHORT);
                            return;
                        }
                        mPresenter.customerAppeal(mOrderNo, reason);
                    }
                })
                .show();
    }

    @Override
    public void onComplete() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoading() {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(this)
                        .build();
            }
            mLoadingDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoaded(GetCustomerIntroDetailResultBean resultDatas) {
        if (resultDatas != null) {
            if (resultDatas.getDatas() != null && resultDatas.getDatas().size() > 0) {
                mDatas.clear();
                mDatas.addAll(resultDatas.getDatas());
                mAdapter.notifyDataSetChanged();
            }

            if (!TextUtils.isEmpty(resultDatas.getAppealInformation())) {
                mBinding.btnAppeal.setEnabled(false);
                mBinding.btnAppeal.setVisibility(View.GONE);
                mBinding.llAppeal.setVisibility(View.VISIBLE);
                mBinding.edtAppeal.setText(resultDatas.getAppealInformation());
                mBinding.tvAppealTime.setText(TextUtils.isEmpty(resultDatas.getAppealTime()) ? "" : resultDatas.getAppealTime());
            }

            String giveupReason = resultDatas.getGiveupReason();
            mBinding.edtGiveupReason.setText(giveupReason);

            mOrderNo = resultDatas.getManagementCode();
        }
        checkNeedShowEmptyView();
    }

    @Override
    public void onError(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        mBinding.btnAppeal.setVisibility(View.GONE);
        checkNeedShowEmptyView();
    }

    @Override
    public void onErrorAppeal(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoadedAppeal(CustomerAppealResultBean datas) {
        ToastManager.show(this, "申诉成功", Toast.LENGTH_SHORT);
        mPresenter.loadDatas(mCompany);
    }

    private void checkNeedShowEmptyView() {
        List<CustomerIntroHistoryResultBean.DatasBean> datas = (List<CustomerIntroHistoryResultBean.DatasBean>) mAdapter.getItems();
        if (datas != null && datas.size() > 0) {
            mBinding.statusLayout.showContentView();
        } else {
            mBinding.statusLayout.showEmptyView();
        }
    }
}
